package com.han.hotelplat.service.hotelmanager.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.han.hotelplat.cache.redis.IRedisCache;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.base.EntityManage;
import com.han.hotelplat.comm.base.Pager;
import com.han.hotelplat.comm.utils.DateUtil;
import com.han.hotelplat.comm.utils.MD5;
import com.han.hotelplat.comm.utils.UUIDUtils;
import com.han.hotelplat.dao.hotel.HotelDao;
import com.han.hotelplat.dao.hotelmanager.HotelmanagerDao;
import com.han.hotelplat.pojo.hhm.HotelHmanager;
import com.han.hotelplat.pojo.hotel.Hotel;
import com.han.hotelplat.pojo.hotelmanager.Hotelmanager;
import com.han.hotelplat.service.hhm.HotelHmanagerService;
import com.han.hotelplat.service.hotelmanager.HotelmanagerService;

@Service
public class HotelmanagerServiceImpl implements HotelmanagerService{
	@Autowired
	private HotelmanagerDao hotelmanagerDao;
	@Autowired
	private HotelDao hotelDao;
	@Autowired
	private IRedisCache redisCache;
	@Autowired
	private  EntityManage entityManage;
	@Autowired
	private  HotelHmanagerService hhmService;
	
	@Override
	public Map<String, Object> login(String phone, String code) {
		Map<String, Object>returndata = new HashMap<String, Object>();
		boolean auth = true;
		for(String whitePhone : Constant.whiteList){
			if(whitePhone.equals(phone)){
				auth=false;
			}
		}
		Hotelmanager hotelmanager = hotelmanagerDao.findByPhone(phone);
		String cachedvcode = redisCache.get(Constant.CACHE_PHONE_VCODE_LOGIN_HM+phone);
		if(auth && !code.equals(cachedvcode)){
			returndata.put("code", -1);
			returndata.put("message", "验证码错误");
			return returndata;
		}
		if(hotelmanager == null){//用户不存在则需要创建新用户
			hotelmanager = new Hotelmanager();
			hotelmanager.setTel(phone);
			hotelmanager.setCreattime(new Date());
			hotelmanager.setUsername(phone);
			hotelmanager.setUserid(UUIDUtils.getUUID()+"");
			hotelmanager.setState(Constant.USER_STATE_CREAT);
			hotelmanagerDao.save(hotelmanager);
		}
		
		hotelmanager.setLastlogintime(new Date());
		hotelmanagerDao.update(hotelmanager);
		if(hotelmanager.getHotelid() == null){//该帮工还未绑定酒店
			hotelmanager.setHotel(null);
		}else{
			Hotel hotel = hotelDao.findById(hotelmanager.getHotelid());
			hotelmanager.setHotel(hotel);
		}
		returndata.put("code", 0);
		returndata.put("message", "登陆成功");
		returndata.put("user", hotelmanager);
		
		redisCache.delete(Constant.CACHE_PHONE_VCODE_LOGIN_HM+phone);
		
		return returndata;
	}

	@Override
	public Map quickLogin(String userid) {
		Hotelmanager hotelmanager = hotelmanagerDao.findByUserid(userid);
		Map<String, Object>returndata = new HashMap<String, Object>();
		if(hotelmanager == null){
			returndata.put("code", -1);
			returndata.put("message", "口令已失效");
			return returndata;
		}
		hotelmanager.setLastlogintime(new Date());
		hotelmanagerDao.update(hotelmanager);
		if(hotelmanager.getHotelid() == null){//该帮工还未绑定酒店
			hotelmanager.setHotel(null);
		}else{
			Hotel hotel = hotelDao.findById(hotelmanager.getHotelid());
			hotelmanager.setHotel(hotel);
		}
		returndata.put("code", 0);
		returndata.put("message", "登陆成功");
		returndata.put("user", hotelmanager);
		return returndata;
	}

	@Override
	public void update(Hotelmanager hotelmanager) {
		hotelmanagerDao.update(hotelmanager);
	}

	@Override
	public Hotelmanager findByUserid(String userid) {
		List<Hotelmanager> li = hotelmanagerDao.findByProperty("userid", userid);
		return li.size()== 0 ? null:li.get(0);
	}

	@Override
	public void save(Hotelmanager hm) {
		hotelmanagerDao.save(hm);
	}

	@Override
	public Map<String, Integer> getHotelCount() {
		String todaysql = "SELECT COUNT(*) FROM tb_hotel WHERE TO_DAYS(date_format(creattime,'%Y-%m-%d')) = TO_DAYS(now())";
		String weeksql = "SELECT COUNT(*) FROM tb_hotel WHERE YEARWEEK(date_format(creattime,'%Y-%m-%d'),1) = YEARWEEK(now())";
		String mothsql = "SELECT  COUNT(*) FROM  tb_hotel WHERE DATE_FORMAT( creattime, '%Y%m' ) = DATE_FORMAT( CURDATE() , '%Y%m' )"; 
		String allsql = "SELECT  COUNT(*) FROM  tb_hotel"; 
		
		List tc = entityManage.findBySql(todaysql);
		List wc = entityManage.findBySql(weeksql);
		List mc = entityManage.findBySql(mothsql);
		List ac = entityManage.findBySql(allsql);
		int todaycount= Integer.parseInt(tc.size() == 0?"0":tc.get(0).toString());//今日
		int weekcount = Integer.parseInt(wc.size() == 0?"0":wc.get(0).toString());//本周
		int monthcount = Integer.parseInt(mc.size() == 0?"0":mc.get(0).toString());//本月
		int allcount = Integer.parseInt(ac.size() == 0?"0":ac.get(0).toString());//本月
		
		Map<String, Integer> data = new HashMap<String, Integer>();
		data.put("todaycount", todaycount);
		data.put("weekcount", weekcount);
		data.put("monthcount", monthcount);
		data.put("allcount", allcount);
		return data;
	}

	@Override
	public Hotelmanager findByTel(String tel) {
		List<Hotelmanager> data = hotelmanagerDao.findByProperty("tel", tel);
		
		return data.size()>0?data.get(0):null;
	}

	@Override
	public Map loginByPassword(String phone, String password) {
		Map<String, Object>returndata = new HashMap<String, Object>();
		Hotelmanager hm = hotelmanagerDao.findByPhone(phone);
		if(hm != null){
			if(hm.getPassword() != null){
				if(hm.getPassword().equals(MD5.toMD5(password))){
					returndata.put("code", 0);
					returndata.put("message", "登陆成功");
					returndata.put("user", hm);
					return returndata;
				}
				returndata.put("code", -1);
				returndata.put("message", "密码错误");
				returndata.put("user", hm);
				return returndata;
			}
			returndata.put("code", -1);
			returndata.put("message", "未设置登陆密码");
			returndata.put("user", hm);
			return returndata;
		}
		returndata.put("code", -1);
		returndata.put("message", "用户不存在");
		returndata.put("user", hm);
		return returndata;
	}

	@Override
	public Pager<Hotelmanager> findHotelManager(int hotelId, String param, int pageNum ) {
		String fromSql = " FROM tb_hotel_manager AS hm "
				+ " LEFT JOIN tb_hotel_hmanager AS hhm "
				+ " ON hhm.hmuserid = hm.userid "
				+ " WHERE 1=1 ";
				
		if(StringUtils.isNotBlank(param)){
			fromSql = fromSql + " AND (hm.realname like '%"+param+"%' "
					+ " OR hm.tel LIKE '%"+param+"%') ";
		}
		
		
		
		String selectSql = "SELECT hm.userid,hm.tel,hm.realname,hm.position,(SELECT COUNT(subhhm.hmuserid) "
				+ " FROM tb_hotel_hmanager AS subhhm "
				+ " WHERE hhm.hmuserid=subhhm.hmuserid and subhhm.state = 1) AS count,hm.sex ";
		
		String sql =selectSql + fromSql + " GROUP BY hm.userid,hm.tel,hm.realname,hm.position,hm.sex";
		Pager data =entityManage.findBySqlPage(sql, fromSql, pageNum, (short)20);
		
		List<Hotelmanager> hmli = new ArrayList<Hotelmanager>();
		List li = data.getList();
		for(int i= 0 ; i<li.size(); i++){
			Object[] ory = (Object[]) li.get(i);
			Hotelmanager hm = new Hotelmanager();
			if(ory[0] != null){//用户ID
				hm.setUserid(ory[0].toString());
			}
			if(ory[1] != null){//电话
				hm.setTel(ory[1].toString());
			}
			if(ory[2] != null){//姓名
				hm.setRealname(ory[2].toString());
			}
			if(ory[3] != null){//职位
				hm.setPosition(Integer.parseInt(ory[3].toString()));
			}
			if(ory[4] != null){//绑定的酒店数量
				hm.setHotelCount(Integer.parseInt(ory[4].toString()));
			}
			if(ory[5] != null){//性别
				hm.setSex(Integer.parseInt(ory[5].toString()));
			}else{
				hm.setSex(1);
			}
			
			String bindCountSql = "SELECT COUNT(*)FROM tb_hotel_hmanager WHERE hotelid=" + hotelId 
					+ " AND state = 1 AND hmuserid='"+ory[0].toString()+"';";
			int count = Integer.parseInt(entityManage.findBySql(bindCountSql).get(0).toString());
			if(count > 0){//已经绑定了
				hm.setIsBindHote(1);
			}else{//未绑定
				hm.setIsBindHote(0);
			}
			hmli.add(hm);
		}
		data.setList(hmli);
		return data;
	}

	@Override
	public List<Hotelmanager> findBindHotelManager(Integer hotelId) {
		String sql = "SELECT hm.userid,hm.tel,hm.realname,hm.position, hm.sex "
				+ " FROM tb_hotel_manager AS hm, tb_hotel_hmanager AS hhm "
				+ " WHERE hhm.hmuserid = hm.userid "
				+ " AND hm.realname is not null  "
				+ " AND hm.tel is not null AND hhm.state = 1 "
				+ " AND hhm.hotelid="+hotelId; 
		List<Hotelmanager> hmli = new ArrayList<Hotelmanager>();
		List li = entityManage.findBySql(sql);
		for(int i= 0 ; i<li.size(); i++){
			Object[] ory = (Object[]) li.get(i);
			Hotelmanager hm = new Hotelmanager();
			if(ory[0] != null){//用户ID
				hm.setUserid(ory[0].toString());
			}
			if(ory[1] != null){//电话
				hm.setTel(ory[1].toString());
			}
			if(ory[2] != null){//姓名
				hm.setRealname(ory[2].toString());
			}
			if(ory[3] != null){//职位
				hm.setPosition(Integer.parseInt(ory[3].toString()));
			}
			if(ory[4] != null){//性别
				hm.setSex(Integer.parseInt(ory[4].toString()));
			}else{
				hm.setSex(1);
			}
			hmli.add(hm);
		}
		return hmli;
	}

	@Override
	public List<Hotelmanager> getBindHotelManager(Integer hotelId, String userid) {
		String sql = "SELECT hm.userid,hm.tel,hm.realname,hm.position, hm.sex, hhm.id"
				+ " FROM tb_hotel_manager AS hm, tb_hotel_hmanager AS hhm "
				+ " WHERE hhm.hmuserid = hm.userid "
				+ " AND hm.tel is not null "
				+ " AND hhm.hotelid = "+hotelId
				+ " AND hhm.hmuserid = '"+ userid +"'"; 
		List<Hotelmanager> hmli = new ArrayList<Hotelmanager>();
		List li = entityManage.findBySql(sql);
		for(int i= 0 ; i<li.size(); i++){
			Object[] ory = (Object[]) li.get(i);
			Hotelmanager hm = new Hotelmanager();
			if(ory[0] != null){//用户ID
				hm.setUserid(ory[0].toString());
			}
			if(ory[1] != null){//电话
				hm.setTel(ory[1].toString());
			}
			if(ory[2] != null){//姓名
				hm.setRealname(ory[2].toString());
			}
			if(ory[3] != null){//职位
				hm.setPosition(Integer.parseInt(ory[3].toString()));
			}
			if(ory[4] != null){//性别
				hm.setSex(Integer.parseInt(ory[4].toString()));
			}else{
				hm.setSex(1);
			}
			hmli.add(hm);
		}
		return hmli;
	}

	@Override
	public Pager<Hotelmanager> findAllHotelManager(String startDate,
			String endDate, Integer position, String param, Integer pageNum) {
		StringBuffer fromSql = new StringBuffer(" FROM tb_hotel_manager AS hm "
				+ " LEFT JOIN tb_hotel_hmanager AS hhm "
				+ " ON hhm.hmuserid = hm.userid where 1=1 " );
		if(StringUtils.isNotBlank(startDate)){
			fromSql.append(" AND hm.creattime >= '" + startDate + " 00:00:00'");
		}
		
		if(StringUtils.isNotBlank(endDate)){
			fromSql.append(" AND hm.creattime <= '" + endDate + " 23:59:59'");
		}

		if(position != null){
			fromSql.append(" AND hm.position = " + position);
		}

		if(StringUtils.isNotBlank(param)){
			fromSql.append(" AND (hm.realname like '%"+param+"%' "
					+ " OR hm.tel LIKE '%"+param+"%' "
					+ " OR hhm.hotelname LIKE '%"+param+"%') ");
		}
		
		
		
		String selectSql = "SELECT hm.userid,hm.tel,hm.realname,hm.position,(SELECT COUNT(subhhm.hmuserid) "
				+ " FROM tb_hotel_hmanager AS subhhm "
				+ " WHERE hhm.hmuserid=subhhm.hmuserid and subhhm.state = 1) AS count , hm.creattime,"
				+ " hm.sex";
		
		String sql =selectSql + fromSql + " GROUP BY hm.userid,hm.tel,hm.realname,hm.position,hm.creattime, hm.sex ORDER BY hm.creattime DESC";
		Pager data =entityManage.findBySqlPage(sql, fromSql.toString(), pageNum, (short)20, "hm.userid");
		
		List<Hotelmanager> hmli = new ArrayList<Hotelmanager>();
		List li = data.getList();
		for(int i= 0 ; i<li.size(); i++){
			Object[] ory = (Object[]) li.get(i);
			Hotelmanager hm = new Hotelmanager();
			if(ory[0] != null){//用户ID
				hm.setUserid(ory[0].toString());
			}
			if(ory[1] != null){//电话
				hm.setTel(ory[1].toString());
			}
			if(ory[2] != null){//姓名
				hm.setRealname(ory[2].toString());
			}
			if(ory[3] != null){//职位
				hm.setPosition(Integer.parseInt(ory[3].toString()));
			}
			if(ory[4] != null){//绑定的酒店数量
				hm.setHotelCount(Integer.parseInt(ory[4].toString()));
			}
			if(ory[5] != null){//创建时间
				hm.setCreattime(DateUtil.parseYMDHMS(ory[5].toString()));
			}
			if(ory[6] != null){//性别
				hm.setSex(Integer.parseInt(ory[6].toString()));
			}else{
				hm.setSex(1);
			}
			hmli.add(hm);
		}
		data.setList(hmli);
		return data;
	}

	@Override
	public Map<String, Integer> getHMCount() {
		String todaysql = "SELECT COUNT(*) FROM tb_hotel_manager WHERE TO_DAYS(date_format(creattime,'%Y-%m-%d')) = TO_DAYS(now())";
		String weeksql = "SELECT COUNT(*) FROM tb_hotel_manager WHERE YEARWEEK(date_format(creattime,'%Y-%m-%d'),1) = YEARWEEK(now())";
		String mothsql = "SELECT  COUNT(*) FROM  tb_hotel_manager WHERE DATE_FORMAT( creattime, '%Y%m' ) = DATE_FORMAT( CURDATE() , '%Y%m' )"; 
		String allsql = "SELECT  COUNT(*) FROM  tb_hotel_manager"; 
		
		List tc = entityManage.findBySql(todaysql);
		List wc = entityManage.findBySql(weeksql);
		List mc = entityManage.findBySql(mothsql);
		List ac = entityManage.findBySql(allsql);
		int todaycount= Integer.parseInt(tc.size() == 0?"0":tc.get(0).toString());//今日
		int weekcount = Integer.parseInt(wc.size() == 0?"0":wc.get(0).toString());//本周
		int monthcount = Integer.parseInt(mc.size() == 0?"0":mc.get(0).toString());//本月
		int allcount = Integer.parseInt(ac.size() == 0?"0":ac.get(0).toString());//所有
		
		Map<String, Integer> data = new HashMap<String, Integer>();
		data.put("todaycount", todaycount);
		data.put("weekcount", weekcount);
		data.put("monthcount", monthcount);
		data.put("allcount", allcount);
		return data;
	}

	@Override
	public Hotelmanager getHMDetailInfo(String userid) {
		Hotelmanager hm = findByUserid(userid);
		List<HotelHmanager> hhm = hhmService.getBindHotelManager(null, userid, 1);
		hm.setHotelList(hhm);
		return hm;
	}

	@Override
	public List<Hotelmanager> exportAllHotelManager(String startDate,
			String endDate, Integer position, String param) {
		StringBuffer fromSql = new StringBuffer(" FROM tb_hotel_manager AS hm "
				+ " LEFT JOIN tb_hotel_hmanager AS hhm "
				+ " ON hhm.hmuserid = hm.userid where 1=1 " );
		if(StringUtils.isNotBlank(startDate)){
			fromSql.append(" AND hm.creattime >= '" + startDate + " 00:00:00'");
		}
		
		if(StringUtils.isNotBlank(endDate)){
			fromSql.append(" AND hm.creattime <= '" + endDate + " 23:59:59'");
		}

		if(position != null){
			fromSql.append(" AND hm.position = " + position);
		}

		if(StringUtils.isNotBlank(param)){
			fromSql.append(" AND (hm.realname like '%"+param+"%' "
					+ " OR hm.tel LIKE '%"+param+"%' "
					+ " OR hhm.hotelname LIKE '%"+param+"%') ");
		}
		
		
		
		String selectSql = "SELECT hm.userid,hm.tel,hm.realname,hm.position,(SELECT COUNT(subhhm.hmuserid) "
				+ " FROM tb_hotel_hmanager AS subhhm "
				+ " WHERE hhm.hmuserid=subhhm.hmuserid and subhhm.state = 1) AS count , hm.creattime,"
				+ " hm.sex";
		
		String sql =selectSql + fromSql + " GROUP BY hm.userid,hm.tel,hm.realname,hm.position,hm.creattime, hm.sex ORDER BY hm.creattime DESC";
		List data =entityManage.findBySql(sql);
		
		List<Hotelmanager> hmli = new ArrayList<Hotelmanager>();
		for(int i= 0 ; i<data.size(); i++){
			Object[] ory = (Object[]) data.get(i);
			Hotelmanager hm = new Hotelmanager();
			if(ory[0] != null){//用户ID
				hm.setUserid(ory[0].toString());
			}
			if(ory[1] != null){//电话
				hm.setTel(ory[1].toString());
			}
			if(ory[2] != null){//姓名
				hm.setRealname(ory[2].toString());
			}
			if(ory[3] != null){//职位
				hm.setPosition(Integer.parseInt(ory[3].toString()));
			}
			if(ory[4] != null){//绑定的酒店数量
				hm.setHotelCount(Integer.parseInt(ory[4].toString()));
			}
			if(ory[5] != null){//创建时间
				hm.setCreattime(DateUtil.parseYMDHMS(ory[5].toString()));
			}
			if(ory[6] != null){//性别
				hm.setSex(Integer.parseInt(ory[6].toString()));
			}else{
				hm.setSex(1);
			}
			hmli.add(hm);
		}
		return hmli;
	}

}
